package com.everflourish.yeah100.act.markingsystem;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseFragment;
import com.everflourish.yeah100.adapter.ProofreadingAdapter;
import com.everflourish.yeah100.entity.marking.ErrorExamitation;
import com.everflourish.yeah100.http.MarkingSystemRequest;
import com.everflourish.yeah100.utils.MyToast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pnikosis.materialishprogress.ProgressWheel;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 校对数据
 * 作者：Created by whf on 2016/6/3.
 * 时间：2016/6/3
 */
public class FragmentProofreading extends BaseFragment implements View.OnClickListener {

    public MarkingMenuActivity mMarkingMenuActivity;
    public RecyclerView mProfRecyclerView;
    private ProgressWheel mProgress;
    private FrameLayout mRefreshFl;
    private List<ErrorExamitation> mList;
    private ProofreadingAdapter mAdapter;
    private MarkingSystemRequest mRequest;
    private TextView mRefreshTv;
    private boolean isPrepared;  //  标志位，标志已经初始化完成。
    private Context mContext;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_proofreading, container,
                false);
        isPrepared = true;
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        initData();
        initWidget();
        configWidget();
        isPrepared = false;
    }

    private void initData() {
        mContext = mMarkingMenuActivity = (MarkingMenuActivity) getActivity();
        mRequest = MarkingSystemRequest.getInstance();
        mList = new ArrayList<>();
        mAdapter = new ProofreadingAdapter(getContext(), mList, mMarkingMenuActivity.mExamination.getLastModifiedTime());
    }

    private void initWidget() {
        mProfRecyclerView = (RecyclerView) getView().findViewById(R.id.RECY_proofreading_list);
        mProgress = (ProgressWheel) getView().findViewById(R.id.proofeading_progress);
        mRefreshFl = (FrameLayout) getView().findViewById(R.id.topic_refresh_fl);
        mRefreshTv = (TextView) getView().findViewById(R.id.include_refresh_tv);
        mRefreshTv.setTextColor(mContext.getResources().getColor(R.color.marking_appbar_primaryDark));
        mRefreshTv.setOnClickListener(this);
    }

    private void configWidget() {
        mProfRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mProfRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mProfRecyclerView.setAdapter(mAdapter);
        mProfRecyclerView.setItemAnimator(new DefaultItemAnimator());

        if (mMarkingMenuActivity.mExamination == null) {
            return;
        }
        getProofeadingList(mMarkingMenuActivity.mExamination.getId());
    }

    /**
     * 获取校对数据列表
     *
     * @param examinationId
     */
    private void getProofeadingList(String examinationId) {
        mProgress.setVisibility(View.VISIBLE);
        JsonObjectRequest request = mRequest.getErrorInfoExaminationRequest(examinationId,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        mProgress.setVisibility(View.GONE);
                        try {
                            if (response.getString("resultCode").equalsIgnoreCase("200026E")) {
                                MyToast.showLong(mContext, "本次阅卷暂无错误信息");
                            }
                            if (response.getString("resultCode").equalsIgnoreCase("000000I")) {
                                String s = response.getJSONArray("automateErrorList").toString();
                                Type type = new TypeToken<List<ErrorExamitation>>() {
                                }.getType();
                                mList = new Gson().fromJson(s, type);
                                mAdapter.reflashDate(mList);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mProgress.setVisibility(View.GONE);
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取校对的数据失败");
                        mRefreshFl.setVisibility(View.VISIBLE);
                    }
                });
        mQueue.add(request);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.topic_add_tv:
                if (mRefreshFl.getVisibility() == View.VISIBLE) {
                    MyToast.showShort(mContext, "请先刷新！");
                    return;
                }
                break;
            case R.id.include_refresh_tv:
                mRefreshTv.setVisibility(View.GONE);
                if (mMarkingMenuActivity.mExamination == null) {
                } else {
                    getProofeadingList(mMarkingMenuActivity.mExamination.getId());
                }
                break;
            default:
                break;
        }
    }

}